<?php

namespace Guardadatos\Model\Dao;

use Zend\Db\TableGateway\TableGateway;
use Guardadatos\Model\Entity\Captura;

class CapturaDao implements ICapturaDao{
    
    protected $tableGateway;
    
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }
    
    public function obtenerPorArticulo($articulo){
        //$id = $id;
        $rowset = $this->tableGateway->select(array('articulo' => "'".$articulo."'"));
        $row = $rowset->current();
        
       /* if($row == null){
            throw new \Exception("Podria no encontrarse la columna con el id: $id");
        }*/
        
        return $row;
        
    }
    
    public function obtenerTodos(){
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }
    
    public function eliminar(Captura $captura){
        $this->tableGateway->delete(array('articulo' => $captura->getArticulo()));
    }
    
    public function guardar(Captura $captura){
        $data = array(
            'campo' => $captura->getCampo(),
            'valorAnterior' => $captura->getValorAnterior(),
            'valorCapturado' => $captura->getValorCapturado(),
            'articulo' => $captura->getArticulo()
        );
        
        $articulo = $captura->getArticulo();
        if($this->obtenerPorArticulo($articulo) == null)
            $this->tableGateway->insert($data);
        else
        {
            $dataActualizar = array(
                'campo' => "'".$captura->getCampo()."'",
                'valorAnterior' => "'".$captura->getValorAnterior()."'",
                'valorCapturado' => "'".$captura->getValorCapturado()."'"
                );
            if($this->obtenerPorArticulo($articulo))
                $this->tableGateway->update($dataActualizar, array('articulo' => $articulo));
            else
                throw new \Exception("Form id does not exist");
        }
         
    }

}


